package com.ljkj.cordial.lengthtcpheartbeat;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;

import java.util.ArrayList;
import java.util.List;

public class NetStateChangeReceiver extends BroadcastReceiver {
    private static class InstanceHolder {
        public static NetStateChangeReceiver INSTANCE = new NetStateChangeReceiver();
    }

    private boolean isConnectNet;

    public boolean isConnectNet() {
        return isConnectNet;
    }

    public void setConnectNet(boolean connectNet) {
        isConnectNet = connectNet;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
            NetworkType networkType = NetworkUtil.getNetworkType(context);
            if (NetworkType.NETWORK_NO == networkType && !isConnectNet()) {
                return;
            } else if (NetworkType.NETWORK_NO != networkType && isConnectNet()) {
                return;
            }
            if (NetworkType.NETWORK_NO == networkType) {
                setConnectNet(false);
            } else {
                setConnectNet(true);
            }
            // do something
            notifyObservers(networkType);
        }
    }

    private void notifyObservers(NetworkType networkType) {
        if (networkType == NetworkType.NETWORK_NO) {
            for (NetStateChangeObserver observer : mObservers) {
                observer.onNetDisconnected();
            }
        } else {
            for (NetStateChangeObserver observer : mObservers) {
                observer.onNetConnected(networkType);
            }
        }
    }

    private List<NetStateChangeObserver> mObservers = new ArrayList<>();

    private static void registerObserver(NetStateChangeObserver observer) {
        if (!InstanceHolder.INSTANCE.mObservers.contains(observer)) {
            InstanceHolder.INSTANCE.mObservers.add(observer);
        }
    }

    private static void unRegisterObserver(NetStateChangeObserver observer) {
        InstanceHolder.INSTANCE.mObservers.remove(observer);
    }

    /**
     * 表示过滤的是网络改变广播
     *
     * @param context
     */
    public static void registerReceiver(Context context, NetStateChangeObserver observer) {
        registerObserver(observer);
        IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(InstanceHolder.INSTANCE, intentFilter);
    }

    public static void unRegisterReceiver(Context context, NetStateChangeObserver observer) {
        unRegisterObserver(observer);
        context.unregisterReceiver(InstanceHolder.INSTANCE);
    }
}
